﻿using System;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using NETMFx.Joystick;
using NETMFx.Math;

#if GHI
using GHIElectronics.NETMF.FEZ;
#endif

#if NETDUINO
using SecretLabs.NETMF.Hardware.Netduino;
#endif

namespace Joystick_Tutorial
{
    public class Program
    {
        public static void Main()
        {
            AnalogJoystick joystick;
#if GHI
            joystick = new AnalogJoystick((Cpu.Pin)FEZ_Pin.AnalogIn.An0, (Cpu.Pin)FEZ_Pin.AnalogIn.An1, -100, 100, 10);
#endif
#if NETDUINO
            joystick = new AnalogJoystick(Pins.GPIO_PIN_A0, Pins.GPIO_PIN_A1, -100, 100, 10);
#endif
            // Calibration values are determined by starting the program with all calibration set to zero.
            // Be sure not to touch the joystick while the program is starting to ensure the automatic center
            // calibration completes correctly. Once values start appearing in the debug window, move the joystick
            // all the way around the circle slowly while pushed as far as it will go.  Record the max values
            // displayed in each direction.  Then find the difference between each of these values and the min or max
            // end of the linear range defined above.  The calibration value will be whatever is necessary to add
            // to the raw value to make it reach the end of the range.
            // Ex.  If linear range is -100 to 100 and we determine that pushing to the far right gives a max
            //      value of 98 then our XCalibration.EndPoints.High = 2  (100-98).
            //
            // A function could easily be added to the AnalogJoystick class to compute this but it would require a coordinated
            // effort between the user and an additional button.  If you decide to create this function, please contribute 
            // back to the library.
            //
            // For help in wiring up the joystick to your NETMF device, see the following blog post.
            // http://blog.ianlee.info/2011/09/using-joystick-with-netmf-and-netmfx.html

            joystick.XCalibration.EndPoints.Low = 0;
            joystick.XCalibration.EndPoints.High = 0;
            joystick.YCalibration.EndPoints.Low = -9;
            joystick.YCalibration.EndPoints.High = 0;
            joystick.AngularCalibration = new Angle(Angle.ConvertDegreesToRadians(-90));

            while (true)
            {
                var x = joystick.Vector.End.X;
                var y = joystick.Vector.End.Y;
                Debug.Print("LEFT  X=" + x + ", Y=" + y + ", Quadrant=" + joystick.Vector.RelativeQuadrant
                            + "  Angle=" + joystick.Vector.Direction.Radians + "  Magnitude=" +
                            joystick.Vector.Magnitude);
                Thread.Sleep(80);
            }
        }
    }
}
